/*
 * @Author: wurangkun
 * @Date: 2024-05-28 20:41:31
 * @LastEditTime: 2024-06-02 13:24:31
 * @LastEditors: wurangkun
 * @FilePath: \my-app\app\pages\camera\index.tsx
 * @Description: 
 */
import { Ionicons } from '@expo/vector-icons';
import { CameraView } from 'expo-camera';
import { CameraType } from 'expo-camera/build/legacy/Camera.types';
import { useNavigation } from 'expo-router';
import { useEffect, useRef, useState } from 'react';
import { Image, Pressable, TouchableOpacity, View, Text, } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import * as ImagePicker from 'expo-image-picker';
import * as MediaLibrary from "expo-media-library"
import Animated, { useSharedValue, withTiming, useAnimatedStyle } from 'react-native-reanimated';
import { px2dp } from '@/hooks/computedPx2Pd';
import MyStyleSheet from '@/hooks/useMySheetStyle';
import dayjs from 'dayjs';

enum CameraSelectType {
  video = 1,
  pic
}

export default function CameraPreview() {
  const [facing, setFacing] = useState(CameraType.back);
  const areaInset = useSafeAreaInsets()
  const navigation = useNavigation();
  const [image, setImage] = useState('')
  const CameraViews = useRef<CameraView>(null);
  const [currentType, setCurrentType] = useState(CameraSelectType.pic);
  const [shottingTime, setShottingTime] = useState(0);
  const [shottingTimer, setShottingTimer] = useState<NodeJS.Timeout>();
  const randomLeft = useSharedValue(0);

  useEffect(() => {
    navigation.setOptions({ headerShown: false });
    getLastPic()
  }, [navigation]);

  const pickImageAsync = async (options?: { single?: boolean, maxlength: number }) => {
    const { single, maxlength } = options || { single: true, maxlength: 1 }
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: single,
      allowsMultipleSelection: !single,
      quality: 1,
    });

    if (!result.canceled) {
      if (single) {
        setImage(result.assets[0].uri)
        console.log(result.assets[0]);
      } else {
        // 如果需要，只保留前几张图片  
        let limitedImages = result.assets
        if (maxlength)
          limitedImages = result.assets.slice(0, maxlength);
        console.log(limitedImages);
      }
    }
  };


  function toggleCameraFacing() {
    setFacing(current => (current === CameraType.back ? CameraType.front : CameraType.back));
  }

  async function cameraOperation() {
    if (currentType === CameraSelectType.pic) {
      await takePicture()
    } else {
      await recording()
    }
  }


  async function takePicture() {
    const res = await CameraViews.current?.takePictureAsync()
    console.log(res)
    if (res) {
      const asset = await MediaLibrary.createAssetAsync(res.uri);
      const b = await MediaLibrary.addAssetsToAlbumAsync(asset.uri, 'Camera');
      console.log(b)
    }
    getLastPic()
  }



  async function recording() {
    if (!shottingTimer) {
      await CameraViews.current?.recordAsync()
      startMeasureTime()
    }
  }

  async function stopRecording() {
    await CameraViews.current?.stopRecording()
    stopMeasureTime()
  }

  // const timer = 

  const startMeasureTime = () => {
    const timer = setInterval(() => {
      setShottingTime(shottingTime + 1)
    }, 1000)
    setShottingTimer(timer)
  }

  const stopMeasureTime = () => {
    clearInterval(shottingTimer)
    setShottingTimer(undefined)
  }

  const getLastPic = async () => {
    const a = await MediaLibrary.getAssetsAsync({ first: 1, sortBy: [MediaLibrary.SortBy.creationTime], mediaType: [MediaLibrary.MediaType.photo] })
    const b = await MediaLibrary.getAssetInfoAsync(a.assets[0].id)
    b.localUri && setImage(b.localUri)
  }

  const handleChangeType = (type: CameraSelectType) => {
    setCurrentType(type)
    randomLeft.value = type === CameraSelectType.pic ? 0 : px2dp(100)
  }

  const leftAnimated = useAnimatedStyle(() => {
    return {
      left: (withTiming(randomLeft.value, {
        duration: 200,
      })),
    };
  });

  return (
    <View style={styles.container}>
      <CameraView ref={CameraViews} style={styles.camera} facing={facing}>
        <View style={styles.buttonContainer}>
          <View style={{ ...styles.button, paddingBottom: areaInset.bottom }}>
            <View>

            </View>
            <View style={styles.CameraType}>
              <View style={styles.CameraTypeItemCover}></View>
              <Animated.View style={[styles.CameraTypeList, leftAnimated]}>
                <Pressable onPress={() => handleChangeType(CameraSelectType.video)}>
                  <View style={styles.CameraTypeItem}>
                    <Text style={{ color: currentType === CameraSelectType.video ? '#000' : '#fff' }}>视频</Text>
                  </View>
                </Pressable>
                <Pressable onPress={() => handleChangeType(CameraSelectType.pic)}>
                  <View style={[styles.CameraTypeItem, {}]}>
                    <Text style={{ color: currentType === CameraSelectType.pic ? '#000' : '#fff' }}>照片</Text>
                  </View>
                </Pressable>
              </Animated.View>
            </View>
            <View style={styles.commonContainer}>
              <TouchableOpacity onPress={toggleCameraFacing}>
                <View style={{ ...styles.buttonLeft, ...styles.commonButton }}>
                  <Ionicons name="sync" size={48} color="white" />
                </View>
              </TouchableOpacity>
              <TouchableOpacity onPress={cameraOperation}>
                <View style={{ ...styles.commonButton, ...styles.buttonCenter }}>
                  <View style={[styles.buttonPlay, { backgroundColor: currentType === CameraSelectType.video ? 'red' : '#fff' }]}></View>
                </View>
              </TouchableOpacity>
              <Pressable onPress={() => pickImageAsync()} style={{ ...styles.buttonRight, ...styles.commonButton }}>
                {
                  image ?
                    <Image src={image} style={{ ...styles.buttonRight, ...styles.commonButton }}></Image>
                    :
                    <Ionicons name="camera" size={36} color="#888" />
                }
              </Pressable>
            </View>
          </View>
        </View>
      </CameraView>
    </View>
  );
}

const styles = MyStyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  camera: {
    flex: 1,
  },
  buttonContainer: {
    flex: 1,
    position: 'relative',
  },
  button: {
    position: 'absolute',
    bottom: 0,
    width: '100%',
    paddingHorizontal: 80,
    paddingVertical: 40,
    flexDirection: 'column',
    justifyContent: "space-between",
    alignItems: "center",
  },
  CameraType: {
    width: 300,
    flexDirection: 'row',
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 80,
    position: "relative",

  },
  CameraTypeList: {
    position: 'absolute',
    flexDirection: 'row',
    justifyContent: "center",
    alignItems: "center",
  },
  CameraTypeItem: {
    width: 100,
    height: 40,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#00000008",

    // backgroundColor: 'red'
  },
  CameraTypeItemText: {

  },
  CameraTypeItemCover: {
    position: "absolute",
    width: 100,
    height: 40,
    backgroundColor: "#ffffff",
    opacity: 0.5,
    borderRadius: 20,
  },
  commonContainer: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: "space-between",
    alignItems: "center",
  },
  commonButton: {
    width: 100,
    height: 100,
  },
  buttonLeft: {
    // backgroundColor: 'red',
    alignItems: "center",
    justifyContent: 'center',
    borderRadius: 20,
  },
  buttonCenter: {
    width: 140,
    height: 140,
    borderRadius: 80,
    borderColor: "#fff",
    borderStyle: "solid",
    borderWidth: 8,
    padding: 6,
  },
  buttonPlay: {
    width: '100%',
    height: '100%',
    borderRadius: 80,
    backgroundColor: '#fff',
  },
  buttonRight: {
    backgroundColor: '#eee',
    alignItems: "center",
    justifyContent: 'center',
    borderRadius: 10,
  },
});